package pers.qianyu.month_202103.date_20210309;

/**
 * 304. 二维区域和检索 - 矩阵不可变
 * https://leetcode-cn.com/problems/range-sum-query-2d-immutable/
 *
 * @author mizzle rain
 * @date 2021-03-09 11:51
 */
public class NumMatrix {
    int[][] pre;

    public NumMatrix(int[][] matrix) {
        int m = matrix.length;
        if (m == 0) {
            return;
        }
        int n = matrix[0].length;
        pre = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                pre[i][j] = matrix[i - 1][j - 1] + pre[i][j - 1] + pre[i - 1][j] - pre[i - 1][j - 1];
            }
        }
        //for (int[] ints : pre) {
        //    System.out.println(Arrays.toString(ints));
        //}
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        if (pre == null) return 0;
        return pre[row2 + 1][col2 + 1] - pre[row1][col2 + 1] - pre[row2 + 1][col1] + pre[row1][col1];
    }

    public static void main(String[] args) {
        int[][] param = {
                {3, 0, 1, 4, 2},
                {5, 6, 3, 2, 1},
                {1, 2, 0, 1, 5},
                {4, 1, 0, 1, 7},
                {1, 0, 3, 0, 5}
        };
        NumMatrix matrix = new NumMatrix(param);
    }
}
